<template>
    <div>
        <titleBar title="位置" rightText="发送" :cb="send"/>
		<div id="container"></div>
		<div class="address">
			<h3 id="title">定位中</h3>
			<p id="address">定位中</p>
		</div>
    </div>
</template>
<script>
import titleBar from '@/components/title_bar/index.vue'
import {clockInDistance} from '@/pages/clockIn/constant.js'
import {AMAPKEY} from '@/utils/amap.js'
import {getuserUid,getUserLogin,getUserInfo,getRole} from '@/utils/auth.js'
let map = "";
let posi = [];
let count = 1;
let loadMap = (site) => {
	//加载地图
    let params = {
        zoom: 16,
		scrollWheel: false,
    }
    map = new AMap.Map('container', params);
	//定位
	AMap.plugin('AMap.Geolocation', function() {
		let geolocation = new AMap.Geolocation({
			enableHighAccuracy: false,//高精度定位
			timeout: 3000,
			buttonPosition:'RB',    //定位按钮的位置
			buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
			zoomToAccuracy: true,
		});
		map.addControl(geolocation);
		//定位成功
		geolocation.getCurrentPosition(function(status,result){
			if(count == 1){
				setTimeout(()=>{
					console.log('重新加载地图');
					count++;
					loadMap();
				},1000)
			}
			console.log(status);
			console.log(result);
		})
	});
	//拖拽选址
	AMapUI.loadUI(['misc/PositionPicker'], function(PositionPicker) {
		console.log(111);
		var positionPicker = new PositionPicker({
            mode: 'dragMap',
            map: map
        });
		//success
		positionPicker.on('success', function(positionResult) {
            console.log(positionResult);
			console.log(positionResult.nearestRoad);
			if(count == 1){
				setTimeout(()=>{
					console.log('重新加载地图');
					count++;
					loadMap();
				},1000)
			}
			//改变内容
			let oTitle = document.getElementById('title');
			let oAddress = document.getElementById('address');
			oTitle.innerHTML = positionResult.regeocode.pois[0].name;
			oAddress.innerHTML = positionResult.address;
			posi = [positionResult.position.lng,positionResult.position.lat]; //经纬度
        });
		//error
		positionPicker.on('fail', function(positionResult) {
            console.log(positionResult);
        });
        positionPicker.start();
	});
}
window.map_callback = () => {
    initAMapUI()
    loadMap()
}
export default {
    components: {
        titleBar
    },
    data(){
        return {
			key:'',
			toast:"",
        }
    },
	mounted(){
		loadMap(this.key, '', '1.4.13')
        .then(AMap => {
          	this.initAmap();
        })
        .catch(() => {
        	console.log('地图加载失败！')
        })
		//this.initAmap();
	},
    created(){
        this.roleId = getRole()?getRole():'';
		this.key = AMAPKEY;
    },
    methods: {
		//加载中
		loading:function(msg){
			const toast = this.$toast.loading({
				duration: 0,
				mask: false,
				message: msg,
				forbidClick:true
			});
			return toast;
		},
		send(){
			if(posi.length == 0){
				this.$toast('发送失败');
			}
			else{
				this.toast = this.loading('发送中');
				let oTitle = document.getElementById('title');
				let oAddress = document.getElementById('address');
				console.log(posi);
				var obj = getUserInfo();
				//扩展字段
				var params = {
					title:this.$store.state.groupTitle,
					orderId:this.$route.query.orderId,
					type:'map',
					name:obj.userName,
					photoUrl:obj.pictureUrl,
					content:posi,
					title:oTitle.innerHTML,
                    time:Date.parse(new Date()),
					address:oAddress.innerHTML,
                    roleId:this.roleId  //PC用到
				};
				HTTP('msg',{
					roomType:"group",
					content:JSON.stringify(posi),
					userUid:getuserUid(),
					groupUid:this.$route.query.id,
					ext:JSON.stringify(params)
				})
				.then(res=>{
					if(res.code == 200){
						setTimeout(()=>{
							this.toast.clear();
							console.log('发送成功');
							this.$router.back();
						},3000)
					}
					else{
						this.$toast(res.msg);
					}
				})
			}
		},
		//初始化地图
        initAmap(){
            if(window.scriptID){
                window.map_callback()
                console.log('已加载成功')
                return
			}
			var scriptID = 'map_amp_ID'
			var amapUIJs = document.createElement('script')
			amapUIJs.src = 'https://webapi.amap.com/ui/1.0/main-async.js'
			document.body.appendChild(amapUIJs)
			amapUIJs.onload = () => {
				var scriptUrl = `https://webapi.amap.com/maps?v=1.4.13&key=${this.key}&callback=map_callback`
				var script = document.createElement('script')
				script.id = scriptID
				script.src = scriptUrl
				document.body.appendChild(script)
			}
			window.scriptID = scriptID
        },
    },
}
</script>
<style lang="scss" scoped>
	#container{
		width: 100%;
		height: calc(100vh - 2.3rem);
	}
	.address{
		width: 100%;
		height: 1rem;
		background-color: #fff;
		padding: 0.2rem 0;
		#title{
			width: 95%;
			font-size: $fz-4;
			margin: 0 auto;
			word-wrap: normal;
			text-overflow: ellipsis;
			white-space: nowrap;
			overflow: hidden;
		}
		#address{
			width: 95%;
			white-space:pre-wrap;
			color: #666;
			margin: 0 auto;
			padding: 2px 0;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
			overflow: hidden;
		}
	}
</style>
